<template>
    <nut-tabbar v-model="selected" class="tabbar-container" size="18px" @tab-switch="handleClick">
        <nut-tabbar-item :tab-title="item.title" :value="item.value" v-for="(item, index) in tabList" :key="index">
            <template #icon="props" style="position: relative">
                <img v-if="props.active" :src="item.activeImg" />
                <img v-else :src="item.img" />
            </template>
        </nut-tabbar-item>
    </nut-tabbar>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { reactive, onMounted, watch } from "vue";
import { useTabbarStore, useUserStore } from "../../store";
import Taro, { eventCenter } from "@tarojs/taro";
const tabbarStore = useTabbarStore();
const userStore = useUserStore();
const { selected, bottomDistance } = storeToRefs(tabbarStore);
const router = Taro.useRouter();

type menu = {
    name: string;
    title: string;
    pagePath: string;
    img: any;
    activeImg: any;
    value: number;
};
watch(selected, (newValue) => {
    // Taro.setStorageSync("selectedTab", newValue);
    tabbarStore.setSelected(newValue)
});
onMounted(() => {
    tabbarStore.setSelected(Taro.getStorageSync("selectedTab") || 0)
    eventCenter.once(router.onReady, () => {
        getTabbarHeight();
    });
});

//计算tabbarBar的高度
const getTabbarHeight = () => {
    const query = Taro.createSelectorQuery()
        .select(".tabbar-container")
        .boundingClientRect();
    query.selectViewport();
    query.exec(function (res) {
        if (res[0]) {
            console.log(res);

            const height = res[0].height;
            tabbarStore.setTabbarHeight(height);
        }
    });
};
const tabList = reactive<menu[]>([
    {
        name: "home",
        title: "首页",
        pagePath: "/pages/home/index",
        img: require("../../assets/tabbar/2/3.png"),
        activeImg: require("../../assets/tabbar/1/3.png"),
        value: 0,
    },
    {
        name: "action",
        title: "订单",
        pagePath: "/pages/order/index",
        img: require("../../assets/tabbar/2/5.png"),
        activeImg: require("../../assets/tabbar/1/5.png"),
        value: 0,
    },
    {
        name: "report",
        title: "我的",
        pagePath: "/pages/mine/index",
        img: require("../../assets/tabbar/2/4.png"),
        activeImg: require("../../assets/tabbar/1/4.png"),
        value: 0,
    },

]);
const handleClick = (item, index: number) => {
    let url = tabList[index].pagePath;

    const pages = Taro.getCurrentPages()
    const currentPage = pages[pages.length - 1]
    if (currentPage.route !== url) {
        handleToPath(url);

    }


};
const handleToPath = (url) => {
    Taro.switchTab({
        url: url,
    });
};
</script>
<style lang="scss">
@import "./customTabBar.scss";
</style>
